home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: gail.ripco.com!mambuhl
- From: mambuhl@ripco.com (Martin Ambuhl)
- Subject: Re: Can a function return
- X-Nntp-Posting-Host: foley.ripco.com
- Message-ID: <DLwwKu.3DA@rci.ripco.com>
- Sender: usenet@rci.ripco.com (Net News Admin)
- Organization: Ripco Internet BBS Chicago
- Date: Sun, 28 Jan 1996 22:17:18 GMT
- X-Ident-Sender: mambuhl
-
- "John D. Hourihane" <hourihaj@iol.ie> in <4ebaaa$jh6@barnacle.iol.ie>
- asks:
-
- >I am trying to write a function which will return a pointer to a function,
- >but I'm having no luck.
-
- See the suggestion below in the code.
-
- >The toy program below illustrates (I hope) what I want to be able to do,
- >but as it stands it won't compile for me. The idea is that the call to
- >'(pick(ADD))' will return a pointer to the 'add' function which is then
- >dereferenced and used.
-
- >But like I say, it doesn't compile. It complains 'Declaration terminated
- >incorrectly' as I declare 'pick'. I'm using Turbo C/C++.
-
- >Any reply, posted here or by email, would be great.
-
- >PHiL
-
- >/* The toy program, to use a function that returns a
- > * pointer to a function.
- > */
-
- >#include <stdio.h>
-
- >#define ADD 0
- >#define MULTIPLY 1
-
- >int add(int x, int y);
- >int multiply(int x, int y);
-
- >/* pick returns a pointer to a function which will operate on two integers */
-
- REPLACE:
- >(int f(int, int)) *pick(int s);
- WITH:
- typedef int (*PFNC) (int, int); /* mha */
- PFNC pick(int s); /* mha */
-
- >int main()
- >{
- > printf("5 + 4 = %d\n", (*(pick(ADD)))(5,4));
- > printf("5 * 4 = %d\n", (*(pick(MULTIPLY)))(5,4));
-
- There is nothing wrong with the above, but neither is there anything
- wrong with the (easier to my eye):
- printf("5 + 4 = %d\n", pick(ADD) (5, 4)); /* mha */
- printf("5 * 4 = %d\n", pick(MULTIPLY) (5, 4)); /* mha */
-
- > return 0;
- >}
-
- >int add(int x, int y)
- >{ return x + y; }
-
- >int multiply(int x, int y)
- >{ return x * y; }
-
- REPLACE:
- >(int f(int, int)) *pick(int s)
- WITH:
- PFNC pick(int s) /* mha */
-
- >{ if (s == ADD)
- > return add;
- > return multiply;
- >}
-
- --
- * Martin Ambuhl net: mambuhl@ripco.com
- * Chicago, IL (USA)
-